package com.css.fxfzysx.modules.cztDataMange.repository.impl;

import com.css.fxfzysx.constants.RelationConstants;
import com.css.fxfzysx.modules.cztDataMange.entity.*;
import com.css.fxfzysx.modules.cztDataMange.repository.BacInformationRepository;
import com.css.fxfzysx.modules.cztDataMange.vo.ExportRcpExcelSheet1Vo;
import com.css.fxfzysx.modules.cztDataMange.vo.QueryBacInformationVo;
import com.css.fxfzysx.modules.cztDataMange.vo.QueryBasicVo;
import com.css.fxfzysx.modules.vabStructure.entity.cztSeismicTimeHistoryEntity;
import com.css.fxfzysx.modules.vabStructure.param.CustomVulnerabilityParam;
import com.css.fxfzysx.util.CreateGson;
import com.css.fxfzysx.util.PlatformObjectUtils;
import com.css.fxfzysx.zcpt.sys.entity.SUser;
import com.css.fxfzysx.zcpt.sys.service.SUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

@Repository
public class BacInformationRepositoryImpl implements BacInformationRepository {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    private SUserService sUserService;

    @Override
    public void saveBvInformation(CbvInfoEntity cb) {
        String sql = "insert into "+RelationConstants.getConstant(cb.getProvince())+"(cbvi_id,intensity,damage,province,city,county,use0,structure_type,years," +
                "fortification,cs,create_user,create_time,del_flag,use1,structure_type1,data_type,number,user_name,basic_library,curve_or_matrix,sd_mr,md_mr,ed_mr,collapse_mr,sd_br,ed_br,md_br,collapse_br" +
                ")values(:cbviId,:intensity,:damage,:province,:city,:county,:use0,:structureType,:years," +
                ":fortification,:cs,:createUser,:createTime,:delFlag,:use1,:structureType1,:dataType,:number,:userName,:basicLibrary,:curveOrMatrix,:sdMr,:mdMr,:edMr,:collapseMr,:sdBr,:edBr,:mdBr,:collapseBr)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(cb);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void savePobStructure(CbcpInfoEntity cb) {
        jdbcTemplate.update("insert into czt_brick_concrete_param_info(cbcpi_id,purpose,province,city,county,structure_type,structure_type1,fortification,years," +
                        "floor,mortar,out_thickness,inner_thickness,width,length,total_floor,section_area,build_area,ci,create_user,create_time,del_flag,purpose1,data_type,number,user_name,comment_info,annex,correction_coefficient,calculate_or_not,basic_library,ci_type1,ci_type1_value,ci_type2,ci_type2_value,ci_type3,ci_type3_value,ci_type4,ci_type4_value,spacing)values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                cb.getCbcpiId(), cb.getPurpose(), cb.getProvince(), cb.getCity(), cb.getCounty(), cb.getStructureType(), cb.getStructureType1(), cb.getFortification(), cb.getYears(),
                cb.getFloor(), cb.getMortar(), cb.getOutThickness(), cb.getInnerThickness(), cb.getWidth(), cb.getLength(), cb.getTotalFloor(), cb.getSectionArea(),
                cb.getBuildArea(), cb.getCi(), cb.getCreateUser(), cb.getCreateTime(), cb.getDelFlag(), cb.getPurpose1(), cb.getDataType(), cb.getNumber(), cb.getUserName(), cb.getCommentInfo(), cb.getAnnex(), cb.getCorrectionCoefficient(), cb.getCalculateOrNot(), cb.getBasicLibrary(), cb.getCiType1(), cb.getCiType1Value(), cb.getCiType2(), cb.getCiType2Value(),
                cb.getCiType3(), cb.getCiType3Value(), cb.getCiType4(), cb.getCiType4Value(), cb.getSpacing());
    }

    @Override
    public void savePobStructure1(CbcbInfoEntity entity) {
        String sql = "insert into czt_brick_concrete_building_info(cbcbi_id,number,building_number,purpose,purpose1," +
                "province,city,county,fortification,years,out_thickness,inner_thickness,total_floor,floor," +
                "structure_type,structure_type1,create_user,create_time,del_flag,data_type,annex,user_name," +
                "basic_library,calculate_or_not,comment_info,ci_type1,ci_type1_value,ci_type2,ci_type2_value," +
                "ci_type3,ci_type3_value,ci_type4,ci_type4_value,spacing,extends1,extends2,extends3,extends4,extends5," +
                "ci,correction_coefficient,table_id,version_id)" +
                "values(:cbcbiId,:number,:buildingNumber,:purpose,:purpose1,:province,:city,:county,:fortification," +
                ":years,:outThickness,:innerThickness,:totalFloor,:floor,:structureType,:structureType1,:createUser," +
                ":createTime,:delFlag,:dataType,:annex,:userName,:basicLibrary,:calculateOrNot,:commentInfo,:ciType1," +
                ":ciType1Value,:ciType2,:ciType2Value,:ciType3,:ciType3Value,:ciType4,:ciType4Value,:spacing,:extends1," +
                ":extends2,:extends3,:extends4,:extends5,:ci,:correctionCoefficient,:tableId,:versionId)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(entity);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void savePobStructure2(CbcbDetailEntity entity) {
        String sql = "insert into czt_brick_concrete_building_detail(cbcbd_id,floor_number,width,length,section_area," +
                "build_area,mortar,cbcbi_id,create_user,create_time,del_flag,comment_info,extends1,extends2,extends3," +
                "extends4,extends5)" +
                "values(:cbcbdId,:floorNumber,:width,:length,:sectionArea,:buildArea,:mortar,:cbcbiId,:createUser," +
                ":createTime,:delFlag,:commentInfo,:extends1,:extends2,:extends3,:extends4,:extends5)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(entity);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void saveRcpInformation(RcpInformationEntity rcp) {
/*        jdbcTemplate.update("insert into czt_concrete_param_info(ccpi_id,intensity,damage,province,city,county,purpose,structure_type,years,fortification,cs," +
                        "pillar_code,truss_spacing,span,floor_num,pillar_height,pillar_section_width,pillar_section_height,fyk,portrait_sectional_area,h0,fck,bk,total_span," +
                        "distance,beam_heigth,board_thickness,concrete_code,fvk,spacing,sectional_area,ash,beam_section_width,beam_section_height,am,has_tcq,en,fvk_strength," +
                        "wall_sectional_area,sectional_ash,jkb,floor_height,live_load,create_user,create_time,del_flag,purpose1,structure_type1,data_type,number,user_name,entirety_id,s2,fyvk,pillarPosition)values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?," +
                        "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", rcp.getCcpiId(),
                rcp.getPillarCode(), rcp.getTrussSpacing(), rcp.getSpan(), rcp.getFloorNum(), rcp.getPillarHeight(), rcp.getPillarSectionWidth(),
                rcp.getPillarSectionHeight(), rcp.getFyk(), rcp.getPortraitSectionalArea(), rcp.getH0(), rcp.getFck(), rcp.getBk(), rcp.getTotalSpan(), rcp.getDistance(),
                rcp.getBoardThickness(), rcp.getConcreteCode(), rcp.getFvk(), rcp.getSpacing(), rcp.getSectionalArea(), rcp.getAsh(),
                rcp.getAm(), rcp.getHasTcq(), rcp.getEn(), rcp.getFvkStrength(), rcp.getWallSectionalArea(), rcp.getSectionalAsh(), rcp.getJkb(), rcp.getFloorHeight(), rcp.getLiveLoad(), rcp.getCreateUser(),
                rcp.getCreateTime(), rcp.getDelFlag(), rcp.getDataType(), rcp.getUserName(), rcp.getEntiretyId(), rcp.getS2(), rcp.getFyvk(), rcp.getPillarPosition());*/
    }

    @Override
    public void savePsaData(CpvAnalysisEntity da) {
        jdbcTemplate.update("insert into czt_probability_vulnerability_analysis(cpva_id,dzd_params,response_params,dzd_params_log,response_params_log,create_user,create_time,del_flag,data_type,number,user_name,cpvi_id)values (?,?,?,?,?,?,?,?,?,?,?,?)",
                da.getCpvaId(), da.getDzdParams(), da.getResponseParams(), da.getDzdParamsLog(), da.getResponseParamsLog(), da.getCreateUser(), da.getCreateTime(), da.getDelFlag(), da.getDataType(), da.getNumber(), da.getUserName(), da.getCpviId());
    }

    @Override
    public void saveCpvInfoEntity(CpvInfoEntity entity) {
        jdbcTemplate.update("insert into czt_probability_vulnerability_info(cpvi_id,purpose0,number,purpose1" +
                        ",province,city,county,structure_type0,structure_type1,fortification,years,create_user,create_time," +
                        "del_flag,comment_info,param1,param2,param3,param4,mc_sd,m_sd1,m_sd2,pc_sd,p_sd1,p_sd2,mc_md" +
                        ",m_md1,m_md2,pc_md,p_md1,p_md2,mc_ed,m_ed1,m_ed2,pc_ed,p_ed1,p_ed2,mc_cd,m_cd1,m_cd2,pc_cd" +
                        ",p_cd1,p_cd2,create_unit,interval_value,calculate_or_not,cs,start_value,end_value,data_type,basic_library,srv_id,gmrcp_id)values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?," +
                        "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                entity.getCpviId(), entity.getPurpose0(), entity.getNumber(), entity.getPurpose1(), entity.getProvince(),
                entity.getCity(), entity.getCounty(), entity.getStructureType0(), entity.getStructureType1(),
                entity.getFortification(), entity.getYears(), entity.getCreateUser(), entity.getCreateTime(), entity.getDelFlag(),
                entity.getCommentInfo(), entity.getParam1(), entity.getParam2(), entity.getParam3(), entity.getParam4(),
                entity.getMcSd(), entity.getMSd1(), entity.getMSd2(), entity.getPcSd(), entity.getPSd1(), entity.getPSd2(),
                entity.getMcMd(), entity.getMMd1(), entity.getMMd2(), entity.getPcMd(), entity.getPMd1(), entity.getPMd2(),
                entity.getMcEd(), entity.getMEd1(), entity.getMEd2(), entity.getPcEd(), entity.getPEd1(), entity.getPEd2(),
                entity.getMcCd(), entity.getMCd1(), entity.getMCd2(), entity.getPcCd(), entity.getPCd1(), entity.getPCd2(), entity.getCreateUnit(), entity.getIntervalValue(), entity.getCalculateOrNot(), entity.getCs(),
                entity.getStartValue(), entity.getEndValue(), entity.getDataType(), entity.getBasicLibrary(), entity.getSrvId(), entity.getGmrcpId());
    }

    @Override
    public void saveCpvResultEntity(CpvResultEntity entity) {
        jdbcTemplate.update("insert into czt_probability_vulnerability_result(cpvr_id,cpvi_id,im,fim,sum,correction_value,create_user," +
                        "create_time,del_flag,break_state)values (?,?,?,?,?,?,?,?,?,?)",
                entity.getCpvrId(), entity.getCpviId(), entity.getIm(), entity.getFim(),
                entity.getSum(), entity.getCorrectionValue(), entity.getCreateUser(), entity.getCreateTime(), entity.getDelFlag(), entity.getBreakState());
    }

    @Override
    public void updateCbv(CbvInfoEntity cbvInfo) {
        String sql = "update "+RelationConstants.getConstant(cbvInfo.getProvince())+" set use0 = :use0,use1 = :use1,cs = :cs,years = :years,info = :info,update_user = :updateUser,update_time = :updateTime where cbvi_id = '"+cbvInfo.getCbviId()+"'";
        SqlParameterSource source = new BeanPropertySqlParameterSource(cbvInfo);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void updateCbc(CbcpInfoEntity cbcInfo) {
        String sql = "update czt_brick_concrete_param_info set purpose= :purpose,province= :province,city= :city,county= :county,structure_type= :structureType,structure_type1= :structureType1," +
                "fortification= :fortification,years= :years,floor= :floor,mortar= :mortar,out_thickness= :outThickness,inner_thickness= :innerThickness," +
                "width= :width,length= :length,total_floor= :totalFloor,section_area= :sectionArea,build_area= :buildArea,ci= :ci,update_user= :updateUser," +
                "update_time= :updateTime,purpose1= :purpose1,comment_info= :commentInfo,annex = :annex, correction_coefficient = :correctionCoefficient,calculate_or_not = :calculateOrNot ci_type1 = :ciType1,ci_type1_value = :ciType1Value, ci_type2 = :ciType2,ci_type2_value = :ciType2Value,ci_type3 = :ciType3,ci_type3_value = :ciType3Value,ci_type4= :ciType4,ci_type4_value = :ciType4Value,spacing =:spacing where cbcpi_id='" + cbcInfo.getCbcpiId() + "'";
        SqlParameterSource source = new BeanPropertySqlParameterSource(cbcInfo);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void updateCbcbInfo(CbcbInfoEntity entity) {
        String sql = "update czt_brick_concrete_building_info set number=:number,building_number=:buildingNumber," +
                "purpose=:purpose,purpose1=:purpose1,province=:province,city=:city,county=:county," +
                "fortification=:fortification,years=:years,out_thickness=:outThickness,inner_thickness=:innerThickness," +
                "total_floor=:totalFloor,floor=:floor,ci_type1=:ciType1,ci_type1_value =:ciType1Value,ci_type2=:ciType2," +
                "ci_type2_value=:ciType2Value,ci_type3=:ciType3,ci_type3_value=:ciType3Value,ci_type4=:ciType4," +
                "ci_type4_value=:ciType4Value,spacing=:spacing,structure_type=:structureType,structure_type1=:structureType1," +
                "update_user=:updateUser,update_time=:updateTime,ci=:ci,correction_coefficient=:correctionCoefficient," +
                "annex=:annex,calculate_or_not=:calculateOrNot,comment_info=:commentInfo " +
                " where cbcbi_id='" + entity.getCbcbiId() + "'";
        SqlParameterSource source = new BeanPropertySqlParameterSource(entity);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void updateCbcbDetail(CbcbDetailEntity entity) {
        String sql = "update czt_brick_concrete_building_detail set floor_number=:floorNumber,width=:width,length=:length," +
                "section_area=:sectionArea,build_area=:buildArea,mortar=:mortar,cbcbi_id=:cbcbiId,comment_info=:commentInfo," +
                "update_user=:updateUser,update_time=:updateTime," +
                " where cbcbd_id='" + entity.getCbcbdId() + "'";
        SqlParameterSource source = new BeanPropertySqlParameterSource(entity);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void updateRcp(RcpInformationEntity rcpInfo) {
        String sql = "update czt_concrete_param_info set intensity= :intensity,damage= :damage,province= :province,city= :city,county= :county,purpose= :purpose," +
                "structure_type= :structureType,years= :years,fortification= :fortification,cs= :cs,pillar_code= :pillarCode,truss_spacing= :trussSpacing,span= :span," +
                "floor_num= :floorNum,pillar_height= :pillarHeight,pillar_section_width= :pillarSectionWidth,pillar_section_height= :pillarSectionHeight,fyk= :fyk," +
                "portrait_sectional_area= :portraitSectionalArea,h0= :h0,fck= :fck,bk= :bk,total_span= :totalSpan,distance= :distance,beam_heigth= :beamHeigth,board_thickness= :boardThickness," +
                "concrete_code= :concreteCode,fvk= :fvk,spacing= :spacing,sectional_area= :sectionalArea,ash= :ash,beam_section_width= :beamSectionWidth,beam_section_height= :beamSectionHeight," +
                "am= :am,has_tcq= :hasTcq,en= :en,fvk_strength= :fvkStrength,wall_sectional_area= :wallSectionalArea,sectional_ash= :sectionalAsh,jkb= :jkb," +
                "floor_height= :floorHeight,live_load= :liveLoad,update_user= :updateUser,update_time= :updateTime,purpose1= :purpose1,structure_type1= :structureType1,s2= :s2,fyvk= :fyvk where ccpi_id='" + rcpInfo.getCcpiId() + "'";
        SqlParameterSource source = new BeanPropertySqlParameterSource(rcpInfo);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void updateHbp(HbpInfoEntity hbpInfo) {
        String sql = "update czt_high_building_param_info set intensity= :intensity,damage= :damage,province= :province,city= :city,county= :county,purpose= :purpose," +
                "structure_type= :structureType,years= :years,fortification= :fortification,cs= :cs,site= :site,build_area= :buildArea,building_height= :buildingHeight," +
                "floor_height= :floorHeight,txzdcjwyj= :txzdcjwyj,update_user= :updateUser,update_time= :updateTime,purpose1= :purpose1,structure_type1= :structureType1,cs1 = :cs1" +
                " where chbpi_id='" + hbpInfo.getChbpiId() + "'";
        SqlParameterSource source = new BeanPropertySqlParameterSource(hbpInfo);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void updateCpv(CpvAnalysisEntity cpvInfo) {
        String sql = "update czt_probability_vulnerability_analysis set dzd_params= :dzdParams,response_params= :responseParams,update_user= :updateUser,update_time= :updateTime where " +
                "cpva_id='" + cpvInfo.getCpvaId() + "'";
        SqlParameterSource source = new BeanPropertySqlParameterSource(cpvInfo);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void updateCpvInfoEntity(CpvInfoEntity entity) {
        String sql = "update czt_probability_vulnerability_info set purpose0=:purpose0,number=:number,purpose1=:purpose1," +
                "province=:province,city=:city,county=:county,structure_type0=:structureType0,structure_type1=:structureType1," +
                "fortification=:fortification,years=:years,del_flag=:delFlag,comment_info=:commentInfo,param1=:param1," +
                "param2=:param2,param3=:param3,param4=:param4,mc_sd=:mcSd,m_sd1=:mSd1,m_sd2=:mSd2,pc_sd=:pcSd,p_sd1=:pSd1," +
                "p_sd2=:pSd2,mc_md=:mcMd,m_md1=:mMd1,m_md2=:mMd2,pc_md=:pcMd,p_md1=:pMd1,p_md2=:pMd2,mc_ed=:mcEd," +
                "m_ed1=:mEd1,m_ed2=:mEd2,pc_ed=:pcEd,p_ed1=:pEd1,p_ed2=:pEd2,mc_cd=:mcCd,m_cd1=:mCd1,m_cd2=:mCd2," +
                "pc_cd=:pcCd,p_cd1=:pCd1,p_cd2=:pCd2,update_user=:updateUser,update_time=:updateTime,interval_value= :intervalValue,start_value= :startValue,end_value =:endValue,calculate_or_not =:calculateOrNot,cs= :cs" +
                " where cpvi_id='" + entity.getCpviId() + "'";
        SqlParameterSource source = new BeanPropertySqlParameterSource(entity);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public boolean deleteCbvById(String id,String province) {
        String sql = "update "+province+" set del_flag = '1' where cbvi_id=?";
        return jdbcTemplate.update(sql, id) > 0;
    }

    @Override
    public boolean deleteCbcbiById(String id) {
        String sql = "update czt_brick_concrete_building_info set del_flag = '1' where cbcbi_id=?";
        return jdbcTemplate.update(sql, id) > 0;
    }

    @Override
    public boolean deleteCbcbDetailById(String cbcbiId) {
        String sql = "update czt_brick_concrete_building_detail set del_flag = '1' where cbcbi_id=?";
        return jdbcTemplate.update(sql, cbcbiId) > 0;
    }

    @Override
    public boolean deleteCbcById(String id) {
        String sql = "update czt_brick_concrete_param_info set del_flag = '1' where cbcpi_id=?";
        return jdbcTemplate.update(sql, id) > 0;
    }

    @Override
    public boolean deleteRcpById(String id) {
        String sql = "update czt_crs_calentirety_result set del_flag = '1' where cal_id=?";
        return jdbcTemplate.update(sql, id) > 0;
    }

    @Override
    public boolean deleteHbpById(String id) {
        String sql = "update czt_high_building_param_info set del_flag = '1' where chbpi_id=?";
        return jdbcTemplate.update(sql, id) > 0;
    }

    @Override
    public boolean deleteCpvById(String id) {
        String sql = "update czt_high_building_param_info set del_flag = '1' where cpva_id=?";
        return jdbcTemplate.update(sql, id) > 0;
    }

    @Override
    public CbcbInfoEntity getCbcbiById(String id) {
        String sql = "select *,(province || '-' || city || '-' || county) region,(structure_type || '-' || structure_type1) st," +
                "(purpose || '-' || purpose1) as use " +
                " from czt_brick_concrete_building_info where del_flag='0' and cbcbi_id='" + id + "'";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(CbcbInfoEntity.class));
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public CbcpInfoEntity getCbcById1(String id) {
        String sql = "select * from czt_brick_concrete_param_info where del_flag='0' and cbcpi_id='" + id + "'";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(CbcpInfoEntity.class));
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public CbcbDetailEntity getCbcbDetailById(String id) {
        String sql = "select * from czt_brick_concrete_building_detail where del_flag='0' and cbcbd_id='" + id + "'";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(CbcbDetailEntity.class));
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public List<CbcbDetailEntity> getCbcbdById(String cbcbiId) {
        String sql = "select * from czt_brick_concrete_building_detail where del_flag='0' and cbcbi_id='" + cbcbiId + "'";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CbcbDetailEntity.class));
    }

    @Override
    public HbpInfoEntity getHbpById(String id) {
        String sql = "select * from czt_high_building_param_info where del_flag='0' and chbpi_id='" + id + "'";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(HbpInfoEntity.class));
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public CpvInfoEntity getCpviById(String id) {
        String sql = "select * from czt_probability_vulnerability_info where del_flag='0' and cpvi_id='" + id + "'";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(CpvInfoEntity.class));
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public HashMap<String, Object> queryBacInformation(QueryBacInformationVo vo, int page, int size) {
        String relation = RelationConstants.getConstant(vo.getProvince());
        StringBuilder sql = new StringBuilder("SELECT * FROM( SELECT cbvi_id AS ID, NUMBER, user_name, province, city, county, structure_type, structure_type1, years, fortification, create_user, create_time, data_type, basic_library, cs, use0, use1, del_flag FROM ").append(relation).append(" UNION ALL SELECT cbcbi_id AS ID, NUMBER, user_name, province, city, county, structure_type, structure_type1, years, fortification, create_user, create_time, data_type, basic_library, FLOOR AS cs, purpose AS use0, purpose1 AS use1, del_flag FROM czt_brick_concrete_building_info UNION ALL SELECT cr.cal_id AS ID, NUMBER, create_user_name as user_name, province, city, county, structure_type, structure_type1, years, fortification, cr.create_user_id AS create_user, cr.create_time, cr.data_type, basic_library, cs, purpose AS use0, purpose1 AS use1, cr.del_flag FROM czt_crs_calentirety_result cr GROUP BY NUMBER, cr.cal_id UNION ALL SELECT chbpi_id AS ID, NUMBER, user_name, province, city, county, structure_type, structure_type1, years, fortification, create_user, create_time, data_type, basic_library, cs, purpose AS use0, purpose1 AS use1, del_flag FROM czt_high_building_param_info) AS result_data WHERE del_flag = '0' ");
        StringBuilder totalSql = new StringBuilder("SELECT count(1) FROM( SELECT cbvi_id AS ID, NUMBER, user_name, province, city, county, structure_type, structure_type1, years, fortification, create_user, create_time, data_type, basic_library, cs, use0, use1, del_flag FROM ").append(relation).append(" UNION ALL SELECT cbcbi_id AS ID, NUMBER, user_name, province, city, county, structure_type, structure_type1, years, fortification, create_user, create_time, data_type, basic_library, FLOOR AS cs, purpose AS use0, purpose1 AS use1, del_flag FROM czt_brick_concrete_building_info UNION ALL SELECT cr.cal_id AS ID, NUMBER, create_user_name as user_name, province, city, county, structure_type, structure_type1, years, fortification, cr.create_user_id AS create_user, cr.create_time, cr.data_type, basic_library, cs, purpose AS use0, purpose1 AS use1, cr.del_flag FROM czt_crs_calentirety_result cr GROUP BY NUMBER, cr.cal_id UNION ALL SELECT chbpi_id AS ID, NUMBER, user_name, province, city, county, structure_type, structure_type1, years, fortification, create_user, create_time, data_type, basic_library, cs, purpose AS use0, purpose1 AS use1, del_flag FROM czt_high_building_param_info) AS result_data WHERE del_flag = '0' ");
        if(!PlatformObjectUtils.isEmpty(vo.getProvince())){
            sql.append(" and province ='" + vo.getProvince() + "'");
            totalSql.append(" and province ='" + vo.getProvince() + "'");
        }
        if(!PlatformObjectUtils.isEmpty(vo.getCity())){
            sql.append(" and city ='" + vo.getCity() + "'");
            totalSql.append(" and city ='" + vo.getCity() + "'");
        }
        if(!PlatformObjectUtils.isEmpty(vo.getCounty())){
            sql.append(" and county ='" + vo.getCounty() + "'");
            totalSql.append(" and county ='" + vo.getCounty() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getDataType())) {
            sql.append(" and data_type ='" + vo.getDataType() + "'");
            totalSql.append(" and data_type ='" + vo.getDataType() + "'");
        }
        if(!PlatformObjectUtils.isEmpty(vo.getUserName())){
            sql.append(" and user_name like'%" + vo.getUserName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getYears())) {
            sql.append(" and years ='" + vo.getYears() + "'");
            totalSql.append(" and years ='" + vo.getYears() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getBasicLibrary())) {
            sql.append(" and basic_library ='" + vo.getBasicLibrary() + "'");
            totalSql.append(" and basic_library ='" + vo.getBasicLibrary() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getCreateStartTime())) {
            sql.append(" and create_time >= '" + vo.getCreateStartTime() + "'");
            totalSql.append(" and create_time >= '" + vo.getCreateStartTime() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getCreateEndTime())) {
            String endTime = vo.getCreateEndTime() + " 23:59:59";
            sql.append(" and create_time <='" + endTime + "'");
            totalSql.append(" and create_time <='" + endTime + "'");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getStructureType())) {
            sql.append(" and structure_type ='" + vo.getStructureType() + "'");
            totalSql.append(" and structure_type ='" + vo.getStructureType() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getStructureType1())) {
            sql.append(" and structure_type1 ='" + vo.getStructureType1() + "'");
            totalSql.append(" and structure_type1 ='" + vo.getStructureType1() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getFortification())) {
            sql.append(" and fortification ='" + vo.getFortification() + "'");
            totalSql.append(" and fortification ='" + vo.getFortification() + "'");
        }
        StringBuilder orderSql = new StringBuilder(" order by create_time desc");
        Integer total = jdbcTemplate.queryForObject(totalSql.toString(), Integer.class);
        StringBuilder limitSql = new StringBuilder(" limit " + size + " offset " + (page - 1) * size);
        sql.append(orderSql).append(limitSql);
        List<QueryBacInformationVo> data = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(QueryBacInformationVo.class));
        data.parallelStream().forEach(it -> {
            if (PlatformObjectUtils.isNotEmpty(it.getCreateUser())) {
                String user = sUserService.getSUser(it.getCreateUser());
                SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
                it.setUserName(sUser.getUserName());
            }
            if (PlatformObjectUtils.isNotEmpty(it.getProvince()) && PlatformObjectUtils.isNotEmpty(it.getCity()) && PlatformObjectUtils.isNotEmpty(it.getCounty())) {
                StringBuilder region = new StringBuilder(it.getProvince()).append("-").append(it.getCity()).append("-").append(it.getCounty());
                it.setRegion(region.toString());
            }
            if (PlatformObjectUtils.isNotEmpty(it.getStructureType())) {
                StringBuilder st = new StringBuilder();
                if (PlatformObjectUtils.isNotEmpty(it.getStructureType1())) {
                    st.append(it.getStructureType()).append("-").append(it.getStructureType1());
                } else {
                    st.append(it.getStructureType());
                }
                it.setSt(st.toString());
            }
        });
        HashMap<String, Object> resultMap = new HashMap();
        resultMap.put("total", total);
        resultMap.put("rows", data);
        return resultMap;
    }

    @Override
    public int getBuildingDataByProvince(String province) {
        try {
            String sql = "select count(cbvi_id) from "+RelationConstants.getConstant(province)+" where del_flag= '0' and province= ?";
            int count = jdbcTemplate.queryForObject(sql, Integer.class, province);
            return count;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public int getBrickDataByProvince(String province) {
        try {
            String sql = "select count(cbcbi_id) from czt_brick_concrete_building_info where del_flag= '0' and province= ?";
            int count = jdbcTemplate.queryForObject(sql, Integer.class, province);
            return count;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public int getBrickDataByProvince1(String province) {
        try {
            String sql = "select count(cbcpi_id) from czt_brick_concrete_param_info where del_flag= '0' and province= ?";
            int count = jdbcTemplate.queryForObject(sql, Integer.class, province);
            return count;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public int getConcreteDataByProvince(String province) {
        try {
            String sql = "select count(chbpi_id) from czt_high_building_param_info where del_flag= '0' and province= ?";
            int count = jdbcTemplate.queryForObject(sql, Integer.class, province);
            return count;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public int getHighDataByProvince(String province) {
        try {
            String sql = "select count(ccpi_id) from czt_concrete_param_info where del_flag= '0' and province= ?";
            int count = jdbcTemplate.queryForObject(sql, Integer.class, province);
            return count;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public int getBuildingHistoryDataByProvince(String province) {
        try {
            String sql = "select count(cbhd_id) from czt_building_history_damage where del_flag= '0' and province= ?";
            int count = jdbcTemplate.queryForObject(sql, Integer.class, province);
            return count;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public List<CpvAnalysisEntity> getCpvAnalysisEntityByCpviId(String cpviId) {
        String sql = "select * from czt_probability_vulnerability_analysis where del_flag='0' and cpvi_id='" + cpviId + "'";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CpvAnalysisEntity.class));
    }

    @Override
    public List<CpvResultEntity> getCpvResultEntityByCpviId(String cpviId) {
        String sql = "select * from czt_probability_vulnerability_result where del_flag='0' and cpvi_id='" + cpviId + "'";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CpvResultEntity.class));
    }

    @Override
    public void updatePsaData(CpvAnalysisEntity cpvAnalysisEntity) {
        jdbcTemplate.update("UPDATE  czt_probability_vulnerability_analysis SET dzd_params=?,response_params=?,dzd_params_log=?,response_params_log=?,update_user=?,update_time=?"
                        + " where cpva_id=?",
                cpvAnalysisEntity.getDzdParams(), cpvAnalysisEntity.getResponseParams(), cpvAnalysisEntity.getDzdParamsLog(), cpvAnalysisEntity.getResponseParamsLog(), cpvAnalysisEntity.getUpdateUser(), cpvAnalysisEntity.getUpdateTime(),
                cpvAnalysisEntity.getCpvaId()
        );
    }


    @Override
    public void moveBasicLibraryById(String dataId, String operate) {
        String sql = "update czt_crs_calentirety_result set basic_library= ? where cbvi_id = ?";
        jdbcTemplate.update(sql, operate, dataId);
    }

    @Override
    public void saveBvInformationValue(CbvInfoMatrixValueEntity cbv) {
        String sql = "insert into czt_building_vulnerability_info_matrix_value(cbvi_value_id,intensity,basically_intact,minor_damage,moderate_damage,serious_damage,collapse,cbvi_id," +
                "create_user,create_time,del_flag" +
                ")values(:cbviValueId,:intensity,:basicallyIntact,:minorDamage,:moderateDamage,:seriousDamage,:collapse,:cbviId," +
                ":createUser,:createTime,:delFlag)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(cbv);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void moveCbvBasicLibraryById(String dataId, String operate,String province) {
        String sql = "update "+RelationConstants.getConstant(province)+" set basic_library= ? where cbvi_id = ?";
        jdbcTemplate.update(sql, operate, dataId);
    }

    @Override
    public void saveCurveValueEntity(CbvInfoCurveValueEntity entity) {
        jdbcTemplate.update("insert into czt_building_vulnerability_info_curve_value  (curve_id,im,fim,sum,create_user,create_time,del_flag,cbvi_id,break_state) values (?,?,?,?,?,?,?,?,?)",
                entity.getCurveId(), entity.getIm(), entity.getFim(), entity.getSum(), entity.getCreateUser(), entity.getCreateTime(), entity.getDelFlag(), entity.getCbviId(), entity.getBreakState());
    }

    @Override
    public CbvInfoEntity getCbvInfoById(String id,String province) {
        String sql = "select * from "+RelationConstants.getConstant(province)+" where del_flag='0' and cbvi_id = '" + id + "'";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(CbvInfoEntity.class));
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public List<CbvInfoMatrixValueEntity> getMatrixByProjectId(String id) {
        String sql = "select * from czt_building_vulnerability_info_matrix_value where del_flag='0' and cbvi_id='" + id + "' order by intensity desc";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CbvInfoMatrixValueEntity.class));
    }

    @Override
    public List<CbvInfoCurveValueEntity> getCbvInfoValueByProjectId(String id) {
        String sql = "select * from czt_building_vulnerability_info_curve_value where cbvi_id='" + id + "' order by sum asc";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CbvInfoCurveValueEntity.class));
    }

    @Override
    public List<ExportRcpExcelSheet1Vo> getRcpInformationById(String id) {
        String sql = "select * from czt_crs_calentirety_result ccr left join" +
                " czt_concrete_param_info ccp on ccr.cal_id = ccp.entirety_id " +
                " left join czt_crs_calroofbeam_result cccr on ccr.cal_id = cccr.entirety_id where ccr.cal_id = '" + id + "'";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ExportRcpExcelSheet1Vo.class));
    }

    @Override
    public void saveCountHbpInfo(HbpInfoEntity entity) {
        jdbcTemplate.update("insert into czt_high_building_param_info  (chbpi_id,intensity,damage,province,city,county,purpose,structure_type,years,fortification,cs,site,build_area,building_height,floor_height,txzdcjwyj6,create_user,create_time,update_user,update_time,del_flag,purpose1,structure_type1,data_type,number,extends1,extends2,extends3,extends4,extends5,extends6,extends7,extends8,extends9,extends10,cs1,calculate_or_not,forecast_results6,emid_angle6,user_name,describe,create_unit,basic_library,correction_coefficient,emid_angle7,emid_angle8,emid_angle9,emid_angle10,txzdcjwyj7,txzdcjwyj8,txzdcjwyj9,txzdcjwyj10,forecast_results7,forecast_results8,forecast_results9,forecast_results10 ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? )",
                entity.getChbpiId(),entity.getIntensity(),entity.getDamage(),entity.getProvince(),entity.getCity(),entity.getCounty(),entity.getPurpose(),entity.getStructureType(),entity.getYears(),entity.getFortification(),entity.getCs(),entity.getSite(),entity.getBuildArea(),entity.getBuildingHeight(),entity.getFloorHeight(),entity.getTxzdcjwyj6(),entity.getCreateUser(),entity.getCreateTime(),entity.getUpdateUser(),entity.getUpdateTime(),entity.getDelFlag(),entity.getPurpose1(),entity.getStructureType1(),entity.getDataType(),entity.getNumber(),entity.getExtends1(),entity.getExtends2(),entity.getExtends3(),entity.getExtends4(),entity.getExtends5(),entity.getExtends6(),entity.getExtends7(),entity.getExtends8(),entity.getExtends9(),entity.getExtends10(),entity.getCs1(),entity.getCalculateOrNot(),entity.getForecastResults6(),entity.getEmidAngle6(),entity.getUserName(),entity.getDescribe(),entity.getCreateUnit(),entity.getBasicLibrary(),entity.getCorrectionCoefficient(),entity.getEmidAngle7(),entity.getEmidAngle8(),entity.getEmidAngle9(),entity.getEmidAngle10(),entity.getTxzdcjwyj7(),entity.getTxzdcjwyj8(),entity.getTxzdcjwyj9(),entity.getTxzdcjwyj10(),entity.getForecastResults7(),entity.getForecastResults8(),entity.getForecastResults9(),entity.getForecastResults10());
    }

    @Override
    public List<Integer> queryBasicLibraryById(String id,String province) {
        String sql = "select count(*) from( select cbvi_id as ID, basic_library, del_flag from "+RelationConstants.getConstant(province)+" union all select cbcbi_id as ID, basic_library, del_flag from czt_brick_concrete_building_info union all select cal_id as ID, basic_library, del_flag from czt_crs_calentirety_result union all select chbpi_id as ID, basic_library, del_flag from czt_high_building_param_info) czt_data where del_flag = '0' and basic_library = '1' and id = '" + id + "'";
        List<Integer> counts = jdbcTemplate.query(sql, new RowMapper<Integer>() {
            @Override
            public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getInt(1);
            }
        });
        return counts;
    }

    @Override
    public void saveSeismicTimeHistory(cztSeismicTimeHistoryEntity it) {
        jdbcTemplate.update("insert into czt_seismic_time_history(id,time,displacement_response,del_flag,cpvi_id) values (?,?,?,?,?)", it.getId(), it.getTime(), it.getDisplacementResponse(), it.getDelFlag(), it.getCpviId());
    }

    @Override
    public void updateMatrixById(CbvInfoMatrixValueEntity entity) {
        jdbcTemplate.update("UPDATE  czt_building_vulnerability_info_matrix_value  SET basically_intact=?,minor_damage=?,moderate_damage=?,serious_damage=?,collapse=?,update_user=?,update_time=?"
                        + " where cbvi_value_id=?",
                entity.getBasicallyIntact(), entity.getMinorDamage(), entity.getModerateDamage(), entity.getSeriousDamage(), entity.getCollapse(), entity.getUpdateUser(), entity.getUpdateTime(),
                entity.getCbviValueId()
        );
    }

    @Override
    public List<QueryBasicVo> queryBasicLibrary(CustomVulnerabilityParam param) {
        try {
            String sql = "SELECT number,pid as id,data_type,province FROM ( SELECT NUMBER , cpvi_id AS pid, province, city, county, structure_type0 AS structure_type, structure_type1, years, fortification, purpose0 AS use0, purpose1 AS use1, create_user, create_time, cs, basic_library, del_flag, data_type FROM czt_probability_vulnerability_info UNION ALL SELECT NUMBER , chbpi_id AS pid, province, city, county, structure_type AS structure_type, structure_type1, years, fortification, purpose AS use0, purpose1 AS use1, create_user, create_time, cs, basic_library, del_flag, data_type FROM czt_high_building_param_info UNION ALL SELECT NUMBER , cal_id AS pid, province, city, county, structure_type AS structure_type, structure_type1, years, fortification, purpose AS use0, purpose1 AS use1, create_user_id AS create_user, create_time, cs, basic_library, del_flag, data_type FROM czt_crs_calentirety_result UNION ALL SELECT NUMBER , cbcbi_id AS pid, province, city, county, structure_type AS structure_type, structure_type1, years, fortification, purpose AS use0, purpose1 AS use1, create_user, create_time, FLOOR AS cs, basic_library, del_flag, data_type FROM czt_brick_concrete_building_info UNION ALL SELECT NUMBER , matrix_id AS pid, province, city, county, structure_type, structure_type1, years, fortification, use0, use1, create_user, create_time, cs, basic_library, del_flag, data_type FROM czt_building_matrix UNION ALL SELECT NUMBER , cbvi_id AS pid, province, city, county, structure_type, structure_type1, years, fortification, use0, use1, create_user, create_time, cs, basic_library, del_flag, data_type FROM "+RelationConstants.getConstant(param.getProvince())+" ) result_Data  WHERE del_flag = '0' AND basic_library = '1' and province = '"+param.getProvince()+"' and " +
                    "city = '"+param.getCity()+"' and county = '"+param.getCounty()+"' and structure_type = '"+param.getStructureType()+"' " +
                    "and structure_type1 = '"+param.getStructureType1()+"' and years = '"+param.getYears()+"' " +
                    "and fortification = '"+param.getFortification()+"' and use0 = '"+param.getUse0()+"' " +
                    "and use1 = '"+param.getUse1()+"' and cs = '"+param.getCs()+"'";
            return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(QueryBasicVo.class));
        } catch (DataAccessException e) {
            return null;
        }
    }
}
